var express = require('express');
var users = require('./users');
var characters = require('./characters');
var classes = require('./classes');

var app =  module.exports = express.createServer();

app.configure(function(){
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({
        secret: "nac"
    }));
    app.use(app.router);
    app.set('views', __dirname + '/../views');
    app.set('view engine', 'ejs');
    app.set('view options', {
        layout: false,
        open: '<j>',
        close: '</j>'
    });
});

app.configure('development', function(){
    app.use(express['static'](__dirname + '/../web'));
    app.use(express.errorHandler({
        dumpExceptions: true, 
        showStack: true
    }));
});

app.configure('production', function(){
    var oneYear = 31557600000;
    app.use(express['static'](__dirname + '/../web', {
        maxAge: oneYear
    }));
    app.use(express.errorHandler());
});

app.get('/', function(req, res){
    if(isLogin(req)){
        res.redirect('/game');
    }else{
        res.redirect('/login');
    }
});

app.get('/login', function(req, res){
    res.render('login');
});

app.get('/register', function(req, res){
    res.render('register');
});

app.get('/characters', function(req, res){
    if(isLogin(req)){
        characters.getAllForUser(req.session.user, function(err, characters){
            if(err)
                res.send(err);
            else{
                res.render('characters', {
                    characters:characters
                });
            } 
        });
    }else{
        res.redirect('/login');
    }
});

app.get('/create', function(req, res){
    if(isLogin(req)){
        classes.getAll(function(err, results){
            if(err)
                res.send(err);
            else{
                res.render('create', {
                    classes:results
                });
            } 
        });
    }else{
        res.redirect('/login');
    }
});

app.get('/game', function(req, res){
    if(isLogin(req)){
        res.render('game', {
            user:req.session.user
        });
    }else{
        res.redirect('/login');
    }
});

app.get('/logout', function(req, res){
    if(req.session.user){
        users.disconnect(req.session.user.username);
    }    
    req.session.destroy();
    res.redirect('/login');
});

app.post('/register', function(req, res){
    users.register({
        username:req.body.username,
        password:req.body.password,
        character:"",
        sessionId:"",
        connected:false
    },function(err, object){
        if(err)
            res.send(err);
        else{
            res.redirect('/login');
        }
    });
});

app.post('/login', function(req, res){
    users.login({
        username:req.body.username,
        password:req.body.password
    }, req.session.id, function(err, obj){    
        if(err){
            if(err.message == "not registered"){
                res.redirect('/register');
            }else{
                res.send(err);
            }
        }else{
            req.session.user = obj;
            res.cookie('cid', req.session.id, {
                path:'/game'
            });
            res.redirect('/game');
        }
            
    });
});

app.post('/create', function(req, res){
    if(isLogin(req)){
        characters.addCharacter(req.session.user, {
            name:req.body.name,
            clazz:req.body.clazz,
            owner:req.session.user.username,
            x:200,
            y:200
        }, function(err, obj){
            if(err)
                res.send(err);
            else
                res.redirect('/characters');
        });
    }else{
        res.redirect('/login');
    }
});

app.post('/select', function(req, res){
    if(isLogin(req)){
        var name = req.body.name;
        if(name != ""){
            users.setCharacter(req.session.user, name, function(err){
                if(!err){
                    res.redirect('/game');
                }
            });
        }
    }else{
        res.redirect('/login');
    }
});

app.listen(80);
console.log("Express server listening on port %d", app.address().port)


function isLogin(req){
    return req.session.user != undefined;
}